package com.support.widget.util;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Window;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class Tools {

    /**
     * 调用系统拨打电话
     */
    public static void DialCall(Context context, String phoneno) {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneno));
        context.startActivity(intent);
    }

    /**
     * 调用系统拨打电话
     */
    public static void DialCall(Context context, int resouceid) {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + resouceid));
        context.startActivity(intent);
    }

    // 密码
    private static final String user_password = "[a-zA-Z0-9]{6,20}$";

    public static boolean password(String value) {
        return !TextUtils.isEmpty(value) && value.matches(user_password);
    }

    /**
     * 间隔日期计算 计算出指定日期前 小时/天/月 的日期
     *
     * @param date 指定日期
     * @param type 计算小时/天/月
     * @param n    间隔天数
     * @throws ParseException
     */
    public static String getLongTime(String date, int type, int n) {
        Calendar c = Calendar.getInstance(); // 当时的日期和时间
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");

        Date time = null;
        if (TextUtils.isEmpty(date)) {
            time = new Date(System.currentTimeMillis());
        } else {
            try {
                time = new Date(df.parse(date).getTime());
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        c.setTime(time);
        int hour; // 需要更改的小时
        int day; // 需要更改的天数
        switch (type) {
            case 0: // n小时前
                hour = c.get(Calendar.HOUR_OF_DAY) - n;
                c.set(Calendar.HOUR_OF_DAY, hour);
                // System.out.println(df.format(c.getTradeTime()));
                break;

            case 1: // n天前
                day = c.get(Calendar.DAY_OF_YEAR) - n;
                c.set(Calendar.DAY_OF_YEAR, day);
                // System.out.println(df.format(c.getTradeTime()));
                break;

            case 2: // n个月前
                day = c.get(Calendar.MONTH) - n;
                c.set(Calendar.MONTH, day);
                // System.out.println(df.format(c.getTradeTime()));
                break;

            case 3: // n年前
                day = c.get(Calendar.YEAR) - n;
                c.set(Calendar.YEAR, day);
                // System.out.println(df.format(c.getTradeTime()));
                break;

        }
        return df.format(c.getTime());
    }

    /**
     * 取出指定日期之间的所有日期
     *
     * @param start 起始日期
     * @param end   终止日期
     *              <p>
     *              包含start,包含end
     */
    public static List<String> getBtweenDaysList(String start, String end) {
        List<String> list = new ArrayList<String>();
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            long startTime = 0;
            long endTime = 0;
            if (TextUtils.isEmpty(start)) {// 如果为空，默认为当天日期
                startTime = System.currentTimeMillis();
            } else {
                startTime = format.parse(start).getTime();
            }
            if (TextUtils.isEmpty(end)) {// 如果为空，默认为当天日期
                endTime = System.currentTimeMillis();
            } else {
                endTime = format.parse(end).getTime();
            }
            int dayNum = (int) Math.abs((endTime - startTime) / (24 * 60 * 60 * 1000));// 间隔天数
            for (int i = 0; i <= dayNum; i++) {
                list.add(format.format(new Date(startTime - 24 * 60 * 60 * 1000 * i)));
            }

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }

    /* 取得终端唯一标识 */
//    public static String getUniqueSign(Context ctx, String deviceSign) {
//        SystemTool systemTool = new SystemTool(ctx);
//        return deviceSign + "-" + systemTool.getDeviceId();
//    }

    /**
     * 判断当前是否有可用的网络以及网络类型 0：无网络 1：WIFI 2：CMWAP 3：CMNET
     *
     * @param context
     * @return
     */
    public static int isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (NetworkInfo anInfo : info) {
                    if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                        if (anInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            return 1;
                        } else if (anInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                            String extraInfo = anInfo.getExtraInfo();
                            if ("cmwap".equalsIgnoreCase(extraInfo)
                                    || "cmwap:gsm".equalsIgnoreCase(extraInfo)) {
                                return 2;
                            }
                            return 3;
                        }
                    }
                }
            }
        }
        return 0;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        LogUtil.i("屏幕密度：" + scale);
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @param context （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取屏幕宽高，单位像素
     *
     * @param context
     * @return
     */
    public static int[] getScreenPixel(Activity context) {
        // 取得窗口属性
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);

        int[] pics = new int[2];
        // 窗口的宽度
        pics[0] = dm.widthPixels;
        // 窗口高度
        pics[1] = dm.heightPixels;
        LogUtil.i(pics[0] + "*" + pics[1]);
        return pics;
    }

    /**
     * 获得屏幕宽高，单位dp
     *
     * @param context
     * @return
     */
    public static int[] getScreenDp(Activity context) {
        // 取得窗口属性
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);

        int[] dips = new int[2];
        // 窗口的宽度
        dips[0] = px2dip(context, dm.widthPixels);
        // 窗口高度
        dips[1] = px2dip(context, dm.heightPixels);
        return dips;
    }

    /**
     * 获取屏幕宽
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Activity context) {
        int[] pics = getScreenPixel(context);
        return pics[0];
    }

    /**
     * 获取屏幕高
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Activity context) {
        int[] pics = getScreenPixel(context);
        return pics[1];
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String getTimeNow() {
        String paramEndDatem = "";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        Date dateNow = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateNow);
        paramEndDatem = sdf.format(dateNow);
        return paramEndDatem;
    }

    public static String getTimeNow2() {
        String paramEndDatem = "";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

        Date dateNow = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateNow);
        paramEndDatem = sdf.format(dateNow);
        return paramEndDatem;
    }

    public static String getYesterday() {
        String paramEndDatem = "";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        Date dateNow = new Date();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        dateNow = cal.getTime();
        paramEndDatem = sdf.format(dateNow);
        return paramEndDatem;
    }

    public static String getYesterday2() {
        String paramEndDatem = "";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

        Date dateNow = new Date();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        dateNow = cal.getTime();
        paramEndDatem = sdf.format(dateNow);
        return paramEndDatem;
    }


    public static String getTimeDay() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String paramStartDated = "";
        Date dateBefore = new Date();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -1);
        dateBefore = cal.getTime();
        paramStartDated = sdf.format(dateBefore);
        return paramStartDated;
    }

    public static String getTimeMonth() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String paramStartDated = "";
        Date dateBefore = new Date();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -1);
        dateBefore = cal.getTime();
        paramStartDated = sdf.format(dateBefore);
        return paramStartDated;
    }

    public static String getTimeWeak() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String paramStartDated = "";
        Date dateBefore = new Date();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -7);
        dateBefore = cal.getTime();
        paramStartDated = sdf.format(dateBefore);
        return paramStartDated;
    }

    public static String getTimeWeak2() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String paramStartDated = "";
        Date dateBefore = new Date();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -7);
        dateBefore = cal.getTime();
        paramStartDated = sdf.format(dateBefore);
        return paramStartDated;
    }

    public static String getGapcount(String now, String end) {
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        try {
            Date d1 = df.parse(now);
            Date d2 = df.parse(end);
            return (d1.getTime() - d2.getTime()) / (60 * 60 * 1000 * 24) + "";
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return "";
    }

    public static void cancleDialog(Dialog pro, long post_start, long post_end) {
        if (pro != null && (post_start == post_end)) {
            synchronized (Tools.class) {
                if (pro != null && (post_start == post_end)) {
                    pro.cancel();
                }
            }
        }
    }

    public static int getStatusBarHeight(Activity activity) {
        int result;
        Rect rectangle = new Rect();
        Window window = activity.getWindow();
        window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
        int statusBarHeight = rectangle.top;
        int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
        result = contentViewTop - statusBarHeight;
        if (result > 0) {
            return result;
        }
        int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = activity.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
}
